from flask import Blueprint, jsonify, request, current_app
from app.models.blind_box import Product
from app.models.supermarket_application import SupermarketApplication
from sqlalchemy import or_

api_bp = Blueprint('api', __name__, url_prefix='/api')

@api_bp.route('/search_products')
def search_products():
    """搜索商品API"""
    query = request.args.get('q', '')
    
    if not query or len(query) < 2:
        return jsonify({'status': 'error', 'message': '搜索词太短', 'products': []})
    
    # 搜索商品
    products = Product.query.filter(
        or_(
            Product.name.ilike(f'%{query}%'),
            Product.category.ilike(f'%{query}%'),
            Product.brand.ilike(f'%{query}%')
        )
    ).limit(20).all()
    
    # 转换为JSON格式
    products_data = [{
        'product_id': p.product_id,
        'name': p.name,
        'category': p.category,
        'brand': p.brand,
        'original_price': float(p.original_price) if p.original_price else 0,
        'image_url': p.image_url
    } for p in products]
    
    return jsonify({
        'status': 'success',
        'products': products_data
    })

# 其他API接口...

@api_bp.route('/application_count')
def application_count():
    """获取待处理申请数量"""
    count = SupermarketApplication.query.filter_by(status=0).count()
    return jsonify({'count': count}) 